package com.yt.sys.common.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.yt.sys.common.config.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;

/**
 * 支付宝签名验证工具类
 */
@Component
public class AlipaySignatureUtil {

    @Resource
    private AlipayConfig alipayConfig;

    private static AlipaySignatureUtil alipaySignatureUtil;

    @PostConstruct
    public void init() {
        alipaySignatureUtil = this;
        alipaySignatureUtil.alipayConfig = this.alipayConfig;
    }

    /**
     * 验证支付宝签名
     * @param params 回调参数
     * @return 是否验证通过
     */
    public static boolean verifySignature(Map<String, String> params) {
        try {
            return AlipaySignature.rsaCheckV1(params,
                    alipaySignatureUtil.alipayConfig.getAlipayPublicKey(),
                    alipaySignatureUtil.alipayConfig.getCharset(),
                    alipaySignatureUtil.alipayConfig.getSignType());
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return false;
        }
    }
}